define(['jquery', 'template'], ($, template) => {
  class Shortcut {
    constructor () {
      this.bindEvent()
      this.getShopNum()
    }

    bindEvent () {
      $('.shop-cart').on('mouseenter', () => {
        this.showMiniCart()
      })
    }

    bindChoose () {
      const _this = this
      $('.p-choose').off().on('click', function () {
        let $li = $(this).parents('.minicart-pro-item')
        _this.changeSelectState($(this), $li)
      })
    }

    showMiniCart () {
      if (!localStorage.getItem('cart')) return false
      let cart = JSON.parse(localStorage.getItem('cart'))

      if (!cart) return false
      // 计算总价
      const total = this.calcTotal(cart)

      // 渲染商品数据
      $('#cart-list').html(template('minicartTemplate', { shop: cart }))
      // 切换购物车显示状态
      $('.minicart-pro-has').show()
      $('.minicart-pro-empty').hide()

      // 绑定事件
      this.bindChoose()
    }

    changeSelectState ($icon, $li) {
      const index = $li.data('index')
      const icon = $icon.find('i')

      let cart = JSON.parse(localStorage.getItem('cart'))
      cart[index].selected = !cart[index].selected

      if (cart[index].selected) {
        icon.removeClass('icon-choose-no').addClass('icon-choose')
      } else {
        icon.removeClass('icon-choose').addClass('icon-choose-no')
      }

      localStorage.setItem('cart', JSON.stringify(cart))
      this.calcTotal(cart)
    }

    calcTotal(cart) {
      const total = cart.reduce((prev, item) => {
        if(item.selected) {
          prev.originPrice += (item.originPrice * item.num)
          prev.price += (item.price * item.num)
        }
        return prev
      }, { originPrice: 0, price: 0 })
      $('.minicart-pro-tool').html(template('totalTemplate', total))
      return total
    }

    getShopNum () {
      let cart = localStorage.getItem('cart')
      if (cart) {
        cart = JSON.parse(cart)
        this.total = cart.reduce((prev, item) => {
          return prev + item.num
        }, 0)
      } else {
        this.total = 0
      }

      let num = this.total
      if (this.total > 99) num = '99+'

      $('.shopNum').html(num)
    }
  }

  return Shortcut
})
